package com.ruoyi.kenuo.controller;

import java.util.*;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.annotation.LoginUser;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.kenuo.domain.EquVo;
import com.ruoyi.kenuo.domain.LunBo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.kenuo.domain.Equ;
import com.ruoyi.kenuo.service.IEquService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 设备管理Controller
 *
 * @author polo
 * @date 2022-08-23
 */
@Api(tags="设备管理")
@RestController
@RequestMapping("/kenuo/equ")
public class EquController extends BaseController
{
    @Autowired
    private IEquService equService;

    /**
     * 查询设备管理列表
     */
    //@PreAuthorize("@ss.hasPermi('kenuo:equ:list')")
    @GetMapping("/list")
    public TableDataInfo list(@LoginUser LoginUser user, Equ equ)
    {
        startPage();
        List<Equ> list = equService.selectEquList(equ);
        return getDataTable(list);
    }

    @GetMapping("/getLunbo")
    public AjaxResult getLunbo()
    {
        List<LunBo> list = equService.getLunbo();
        return AjaxResult.success(list);
    }
    /**
     * 获取设备总数量/绑定数量、销售数量
     * @param equ
     * @return
     */
    @PostMapping("/getTotalCount")
    public AjaxResult getTotalCount(@RequestBody Equ equ)
    {
        AjaxResult ar = equService.getTotalCount(equ);
        return ar;
    }
    /**
     * 获取本年度销售数量
     * @param equ
     * @return
     */
    @PostMapping("/getYearSaleCount")
    public AjaxResult getYearSaleCount(@RequestBody Equ equ)
    {
        AjaxResult ar = equService.getYearSaleCount(equ);
        return ar;
    }
    /**
     * 根据用户id 查询设备管理列表
     */
    @PostMapping("/getListByUserId")
    public TableDataInfo getListByUserId(@RequestBody EquVo equVo)
    {
        startPage();
        List<EquVo> list = equService.getListByUserId(equVo);
        return getDataTable(list);
    }

    /**
     * 导出设备管理列表
     */
    //@PreAuthorize("@ss.hasPermi('kenuo:equ:export')")
    @Log(title = "设备管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Equ equ)
    {
        List<Equ> list = equService.selectEquList(equ);
        ExcelUtil<Equ> util = new ExcelUtil<Equ>(Equ.class);
        util.exportExcel(response, list, "设备管理数据");
    }

    /**
     * 获取设备管理详细信息
     */
    //@PreAuthorize("@ss.hasPermi('kenuo:equ:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(equService.selectEquById(id));
    }

    /**
     * 新增设备管理
     */
    //@PreAuthorize("@ss.hasPermi('kenuo:equ:add')")
    @Log(title = "设备管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Equ equ)
    {
        String snCode = equ.getEquipmentSn();
        if(StringUtils.isEmpty(snCode)){
            return AjaxResult.error("设备sn码不能为空!");
        }else {
            Equ eu = equService.selectEquBySn(snCode);
            boolean kb = Optional.ofNullable(eu).isPresent();
            if(kb){
                return AjaxResult.error("已经存在相同的sn码设备："+snCode);
            }
            return toAjax(equService.insertEqu(equ));
        }
    }

    /**
     * 修改设备管理
     */
    //@PreAuthorize("@ss.hasPermi('kenuo:equ:edit')")
    @Log(title = "设备管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Equ equ)
    {
        return toAjax(equService.updateEqu(equ));
    }
    /**
     * 下载模板
     */
    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response)
    {
        ExcelUtil<Equ> util = new ExcelUtil<Equ>(Equ.class);
        List<Equ> list = new ArrayList<>();
        Equ e = new Equ();
        e.setEquipmentSn("此行是模板样例：sn12345");
        e.setEquipmentModel("CN-1610");
        e.setBoundPhone("17XXXX13200");
        e.setSaleNel("0");
        list.add(e);
        util.exportExcel(response, list, "设备管理数据");
    }
    @Log(title = "导入设备数据", businessType = BusinessType.IMPORT)
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception
    {
        ExcelUtil<Equ> util = new ExcelUtil<Equ>(Equ.class);
        List<Equ> equMyList = util.importExcel(file.getInputStream());
        //对数据进行去重
        List<Equ> equList = equMyList.stream().collect(
                Collectors.collectingAndThen(
                        Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(Equ::getEquipmentSn))), ArrayList::new)
        );

        if(equList.size()>0){
            equList.forEach(x->{
                Equ eu = equService.selectEquBySn(x.getEquipmentSn());
                boolean kb = Optional.ofNullable(eu).isPresent();
                if(kb){
                    throw new RuntimeException("已经存在相同的sn码设备："+x.getEquipmentSn());
                }
               String tl = x.getBoundPhone();
               if(StringUtils.isNotEmpty(tl)){
                   x.setBoundStatus(2);
                   x.setBoundTime(DateUtils.getNowDate());
               }else {
                   x.setBoundStatus(1);
               }
               x.setCreateTime(DateUtils.getNowDate());
               x.setXsUserId("107");
               x.setXsName("科诺公司");
                equService.insertEqu(x);
            });
        }else {
            return AjaxResult.error("没有要导入的数据");
        }
        return AjaxResult.success("导入成功");
    }
    /**
     * 删除设备管理
     */
    //@PreAuthorize("@ss.hasPermi('kenuo:equ:remove')")
    @Log(title = "设备管理", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids)
    {
        return toAjax(equService.deleteEquByIds(ids));
    }
    @ApiOperation(value="获取首页地图信息", httpMethod = "POST")
    @PostMapping("/getIndexDt")
    public AjaxResult getIndexDt(){
        List<Map<String,Object>> mp = equService.getIndexDt();
        return AjaxResult.success(mp);
    }


}
